package cn.com.zsc.hr;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;

import cn.com.zsc.properties.ReadProperties;
import cn.com.zsc.util.ConstValue;

/**
 * 职工管理Servlet
 * @author 杨景
 *
 */
public class EmployeeManageServlet extends HttpServlet {
	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
		
	/**
	 * doGet
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * 上传图片
	 */
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");
		response.setHeader("charset", "UTF-8");
		
		ReadProperties rp = new ReadProperties();
		
		// 临时文件目录
		String tempPath = rp.getValue("tempPath");
		File tempDir = new File(tempPath);
		
		if(!tempDir.isDirectory()) {
			tempDir.mkdir();
		}
		
		// 保存上传文件目录
		String photoPath = rp.getValue("photoPath");
		File saveDir = new File(photoPath);
		
		if(!saveDir.isDirectory()) {
			saveDir.mkdir();
		}
		
		try {
			if(ServletFileUpload.isMultipartContent(request)) {
				// 创建该对象
				DiskFileItemFactory dff = new DiskFileItemFactory();
				
				// 指定上传文件的临时目录
				dff.setRepository(tempDir);
				
				// 指定在内存中缓存数据大小，单位为byte
				dff.setSizeThreshold(1024000);
				
				// 创建该对象
				ServletFileUpload sfu = new ServletFileUpload(dff);
				
				// 指定单个上传文件的最大尺寸
				sfu.setFileSizeMax(5000000);
				
				// 指定一次上传多个文件的总尺寸
				sfu.setSizeMax(10000000);
				
				// 解析request请求，并返回FileItemIterator集合
				List<FileItem> fileItemList = sfu.parseRequest(request);
				
				// 将普通表单域放入map
				HashMap<String, String> map = new HashMap<String, String>();
				
				// 操作类型 0：新增 1：修改
				int operateType =  -1;
				
				int isFormal = -1;
				
				if(!fileItemList.isEmpty()) {
					for (int i=0; i<fileItemList.size(); i++) {
						FileItem fi = fileItemList.get(i);
						
						// 是普通表单域
						if(fi.isFormField()) {						
							if("operateType".equals(fi.getFieldName())) {
								operateType = Integer.parseInt(fi.getString("UTF-8"));
							} else {
								// 将请选择替换为空字符串
								map.put(fi.getFieldName(), "请选择".equals(fi.getString("UTF-8"))?"":fi.getString("UTF-8"));
								
								if("isFormal".equals(fi.getFieldName())) {
									isFormal = Integer.parseInt(fi.getString("UTF-8"));
								}
							}
					    // 是文件域
						} else {
							// 本地文件全路径名
							String fileName = fi.getName();
							
							// 如果没有上传照片
							if(StringUtils.isEmpty(fileName)) {
								map.put("photo", "");
							} else {
								// 根据时间修改文件名
								fileName = new Date().getTime() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
								
								// 保存照片的全路径文件名
								String fullPathName = saveDir + "\\" + fileName;
								
								// 保存文件
								fi.write(new File(fullPathName));
								
								map.put("photo", fullPathName);
							}
						}
					}
				}
				
				if (isFormal == ConstValue.PL_CODE_41) {
					map.put("sino", "");
					map.put("contract", "");
					map.put("signDate", "");
					map.put("limitDate", "");
					map.put("starLevel", "");
					map.put("tPost", "");
					map.put("cCard", "");
					map.put("eLevel", "");
					map.put("mLevel", "");
					map.put("rp", "");
				} else {							
					map.put("special", "");
					map.put("inDate", "");
					map.put("graduation", "");
					map.put("agreement", "");
					map.put("endDate", "");
					map.put("teacher", "");
					map.put("insurance", "");
				}
				
			    // 将map转换为json字符串
				JSONArray json = JSONArray.fromObject(map);
				String jsonStr = json.toString();
				jsonStr = jsonStr.substring(1, jsonStr.length() - 1);
				
				String result = "";
				if (operateType == 0) {
					// 执行新增操作
					result = new EmployeeManage().insertEmployee(jsonStr);
				} else {
					// 执行新增操作
					result = new EmployeeManage().updateEmployee(jsonStr);
				}
								
				if ("success".equals(result)) {
					response.getWriter().print("{success:true}");
				} else {
					response.getWriter().print("{success:false}");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
